package com.kyzh.core.uis


import android.app.Activity
import android.content.Context
import android.view.View
import android.widget.TextView
import androidx.appcompat.app.AlertDialog
import androidx.core.content.ContextCompat
import com.gushenge.core.base.Base
import com.gushenge.core.dao.GlobalKeys
import com.kyzh.core.R
import com.kyzh.core.activities.BrowserActivity
import com.kyzh.core.utils.startActivity
import io.github.armcha.autolink.AutoLinkTextView
import io.github.armcha.autolink.MODE_URL


private var pactDialog: AlertDialog? = null

fun Activity.showPactView(listener: Boolean.() -> Unit) {
    val spSurePact =
        with(getSharedPreferences("spSurePactfile", Context.MODE_PRIVATE)) {
            getBoolean("spSurePact", false)
        }
    if (!spSurePact) {
        pactDialog = AlertDialog.Builder(this, R.style.kyzhGuestLoginDialog)
                .setView(getPactView(listener))
                .setCancelable(false).create()

        pactDialog?.show()
    }else{
        listener(true)
    }
}

private fun Activity.getPactView(listener: Boolean.() -> Unit): View {
    val view = View.inflate(this, R.layout.dialog_pact, null)

    val tvContent = view.findViewById<AutoLinkTextView>(R.id.tvContent)
    val cancel = view.findViewById<TextView>(R.id.tv2)
    val sure = view.findViewById<TextView>(R.id.tv3)

    tvContent.addAutoLinkMode(
            MODE_URL
    )
    tvContent.addUrlTransformations(
            "https://www.google.com" to "《${getString(R.string.registerAgreement)}》",
            "https://www.baidu.com" to "《${getString(R.string.privacyPolicy)}》"
    )
    tvContent.urlModeColor = ContextCompat.getColor(this, R.color.colorPrimary)
    tvContent.text = getString(R.string.pactDialogDesc)

    tvContent.onAutoLinkClick {
        if (it.transformedText.equals("《${getString(R.string.registerAgreement)}》")) {
            /*协议*/
            val REGISTER_PACT = "${Base.BASEURL}/?ct=zhanwu&ac=agreement&id=1"

            startActivity<BrowserActivity>(GlobalKeys.TITLE to getString(R.string.registerAgreement) , GlobalKeys.LINK to REGISTER_PACT)
        } else {
            val PRIVACY_PACT = "${Base.BASEURL}/?ct=zhanwu&ac=agreement&id=2"
            startActivity<BrowserActivity>(GlobalKeys.TITLE to getString(R.string.privacyPolicy), GlobalKeys.LINK to PRIVACY_PACT)
        }
    }


    cancel.setOnClickListener {
        pactDialog?.dismiss()
        listener(false)
        finish()
    }
    sure.setOnClickListener {
        pactDialog?.dismiss()
        listener(true)
    }
    return view
}
